import React, {forwardRef, useImperativeHandle, useRef, useState} from 'react';
import ImageGallery from "@/app/yolo/sign/image-gallery";

interface ImageUploaderProps {
    onData: (image: { name: string; src: string }) => void
}

type ChildHandle = {
    selectNextImage: () => void
};

// eslint-disable-next-line react/display-name
const ImageUploader= forwardRef<ChildHandle, ImageUploaderProps>((props, ref) => {

    const {onData} = props;

    const [images, setImages] = useState<{ name: string; src: string }[]>([]);


    // gallery 组件
    const imageGalleryRef =  useRef<{
        gallerySelectNextImage: () => void
    }>(null);


    useImperativeHandle(ref, () => ({
        selectNextImage: () => {
            console.log("image-uploader selectNextImage1",imageGalleryRef)
            imageGalleryRef.current?.gallerySelectNextImage();
            console.log("image-uploader selectNextImage2")
        }
    }));


    // 处理文件选择的逻辑
    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const files = event.target.files;
        if (!files) return;

        // 读取文件并转换为 Data URL
        const imagePromises = Array.from(files).map((file) => {
            return new Promise<{ name: string; src: string }>((resolve) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    if (e.target?.result) {
                        resolve({name: file.name, src: e.target.result as string});
                    }
                };
                reader.readAsDataURL(file);
            });
        });

        // 更新组件状态
        Promise.all(imagePromises).then((imageDataUrls) => {
            setImages((prev) => [...prev, ...imageDataUrls]);
        });
    };

    // 触发 onData 回调
    const onDataHandler = (image: { name: string; src: string }) => {
        onData(image);
    };

    return (
        <div>
            <input
                className="file-input w-full max-w-xs input-sm"
                type="file"
                id="fileInput"
                accept="image/*"
                multiple
                // 强制类型断言，允许 webkitdirectory 属性
                {...({webkitdirectory: "true"} as React.InputHTMLAttributes<HTMLInputElement>)}
                onChange={handleFileChange}
            />
            <div id="imageContainer" className="mt-1.5">
                <ImageGallery ref={imageGalleryRef} images={images} onData={onDataHandler}/>
            </div>
        </div>
    );
});

export default ImageUploader;